const jwt = require('jsonwebtoken');

const { JWT_SECRET } = require('@config/config.default');

const {
  tokenExpiredErr,
  tokenInvalidErr,
  notAdminPermission,
} = require('@constant/error.type');

module.exports = {
  async auth(ctx, next) {
    const { authorization = '' } = ctx.request.header;

    const token = authorization.replace('Bearer ', '');

    try {
      const decoded = jwt.verify(token, JWT_SECRET);

      ctx.state.user = decoded;
    } catch (err) {
      const errMap = {
        TokenExpiredError: () => ctx.app.emit('error', tokenExpiredErr, ctx),
        JsonWebTokenError: () => ctx.app.emit('error', tokenInvalidErr, ctx),
      };

      return errMap[err.name]();
    }

    await next();
  },

  async hadAdminPermission(ctx, next) {
    const { is_admin } = ctx.state.user;

    if (is_admin === '0') {
      return ctx.app.emit('error', notAdminPermission, ctx);
    }

    await next();
  },
};
